import array
import os
from collections import namedtuple

# 1.列表推到 、 filter+map
s = '$¢£¥€¤'
ac = [ord(x) for x in s if ord(x) > 127]
print(ac)

ac2 = list(filter(lambda c: c > 127, map(ord, s)))
print(ac2)

# 笛卡尔积
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]
print(tshirts)
tshirts2 = [(color, size) for size in sizes for color in colors]
print(tshirts2)

# 2.生成器表达式(每次生成一个 节省内存开销) 与列表推到类似 [] -> ()
t = tuple(ord(symbol) for symbol in s)  # 函数唯一参数 省略()
print(t)

arr = array.array('I', (ord(symbol) for symbol in s))
print(arr)

# 逐个产出元素
for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
    print(tshirt)

# 3.元组 不可变列表、可用于没有字段名的记录
lax_coordinates = (33.9425, -118.408056)
# 拆包
city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')]
for passport in sorted(traveler_ids):
    print('%s/%s' % passport)

for country, _ in traveler_ids:
    print(country)
# 拆包
latitude, longitude = lax_coordinates
print(latitude)
print(longitude)
a = 10
b = 5
b, a = a, b
print(a)
print(b)
print(divmod(20, 8))
t = (20, 8)
# *号拆包作为函数参数
quotient, remainder = divmod(*t)
print(quotient, remainder)
_, filename = os.path.split('/home/luciano/.ssh/idrsa.pub')
print(filename)
a, b, *rest = range(5)
print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
*head, b, c, d = range(5)
print(head, b, c, d)
# 嵌套元组拆包
metro_areas = [
    ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
    ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
    ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
    ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
    ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
# 占据的位置 ^居中
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas:
    if longitude <= 0:
        print(fmt.format(name, latitude, longitude))

# 具名函数 内存比普通对象实例小一些
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', population=36.933, coordinates=(35.6889722, 139, 691667))
print(tokyo)
print(tokyo.population)
print(tokyo.coordinates)
print(tokyo[1])
# 属性和方法
print(City._fields)
LatLong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
# _make等同City(*delhi_data)
delhi = City._make(delhi_data)
# 以 collections.OrderedDict 的形式返回
print(delhi._asdict())

